﻿using System;
using System.IO;
using System.Text;

namespace Sencha.Serialization
{
	public sealed class JsonTextWriter : JsonWriterBase
	{
		TextWriter m_writer;

		private TextWriter Writer { get { return m_writer; }}

		public JsonTextWriter(TextWriter writer)
			: this(writer, new AdHocSerializer())
		{

		}
		public JsonTextWriter(TextWriter writer, ISerializationContext context)
			: base(context)
		{
			if (writer == null)
				throw new ArgumentNullException("writer");
			System.Diagnostics.Contracts.Contract.EndContractBlock();

			m_writer = writer;
		}

		public override void Flush()
		{
			m_writer.Flush();
		}
		public override void WriteJson(string jsonString)
		{
			if (jsonString == null)
				throw new ArgumentNullException("jsonString");
			System.Diagnostics.Contracts.Contract.EndContractBlock();

			m_writer.Write(jsonString);
			this.CharactersWritten += jsonString.Length;
		}
		public override void WriteJson(char[] jsonString, int offset, int charactersToWrite)
		{
			if (jsonString == null)
				throw new ArgumentNullException("jsonString");
			if (offset < 0 || offset >= jsonString.Length)
				throw new ArgumentOutOfRangeException("offset");
			if (charactersToWrite < 0 || offset + charactersToWrite > jsonString.Length)
				throw new ArgumentOutOfRangeException("charactersToWrite");
			System.Diagnostics.Contracts.Contract.EndContractBlock();

			if (charactersToWrite == 0)
				return;

			m_writer.Write(jsonString, offset, charactersToWrite);
			this.CharactersWritten += charactersToWrite;
		}

		public override string ToString()
		{
			return m_writer.ToString();
		}
	}
}
